
const BASE_URL = getApp().$vm.$global.baseURL

export function addToCart(product, cartCountRef) {
  const userInfo = uni.getStorageSync('userInfo')
  if (!userInfo || !userInfo.id) {
    uni.showToast({ title: '请先登录', icon: 'none' })
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/login/login' })
    }, 1000)
    return
  }

  const userId = userInfo.id
  const cartItem = {
    userId: userId,
    goodId: product.id,
    count: 1,
    standard: product.standard || '100g'
  }

  console.log('准备添加购物车：', cartItem)

  uni.request({
    url: `${BASE_URL}/api/cart`,
    method: 'POST',
    data: cartItem,
    header: {
      'Content-Type': 'application/json'
    },
    success: (res) => {
      console.log('加入购物车响应:', res)
      if (res.data.code === '200') {
        if (cartCountRef && typeof cartCountRef === 'object') {
          cartCountRef.value++  // 通过引用修改调用页面的cartCount
        }
        uni.showToast({ title: '加入成功', icon: 'success' })
      } else {
        uni.showToast({ title: res.data.msg || '添加失败', icon: 'none' })
      }
    },
    fail: (err) => {
      console.error('请求失败:', err)
      uni.showToast({ title: '网络错误', icon: 'none' })
    }
  })
}
